//
//  MainViewController.swift
//  01-SLWeibo
//
//  Created by 李博 on 15/6/23.
//  Copyright © 2015年 libo. All rights reserved.
//

import UIKit

class MainViewController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()

        addChildViewControllers();
        
        //获取tabBar
        let tb = MainTabBar()
        setValue(tb, forKey: "tabBar");
        
        tb.compoesButton.addTarget(self, action: "composedButtonClicked", forControlEvents: UIControlEvents.TouchUpInside)
        
        
    }
    
    ///  点击撰写按钮，按钮监听方法不能私有
    func composedButtonClicked() {
        
        let nav = UINavigationController(rootViewController: ComposeViewController())
        presentViewController(nav, animated: true, completion: nil)
    }
    
    
    private func addChildViewControllers() {
        
        let path = NSBundle.mainBundle().pathForResource("MainVCSettings.json", ofType: nil)!
        let data = NSData(contentsOfFile: path)!
        do {
            
            let array = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments)
            
            //在遍历数组时，必须指明数组中包含对象的类型，包括字典中的格式
            for dict in array as! [[String: String]] {
                addChildViewController(dict["vcName"]!, title: dict["title"]!, imgName: dict["imageName"]!)
            }
        }catch {
            print(error)
            // 如果从网络加载的 json 出错，直接用字符串加载
            addChildViewController("HomeTableViewController", title: "首页", imgName: "tabbar_home")
            addChildViewController("MessageTableViewController", title: "消息", imgName: "tabbar_message_center")
            addChildViewController("DiscoverTableViewController", title: "发现", imgName: "tabbar_discover")
            addChildViewController("ProfileTableViewController", title: "我", imgName: "tabbar_profile")
        }

        
    }
    

    private func addChildViewController(vcName: String,title: String,imgName:String) {
        
        //print(NSBundle.mainBundle().infoDictionary);
        let ns = NSBundle.mainBundle().infoDictionary!["CFBundleExecutable"] as! String
        
        //将字符串转化成类
        let cls:AnyClass = NSClassFromString(ns + "." + vcName)!
        
        //实例化对象
        let vc = cls.new() as! UIViewController
        
        vc.title = title;
        vc.tabBarItem.image = UIImage(named: imgName);
        vc.tabBarItem.selectedImage = UIImage(named: imgName + "_highlighted");
        
        let nav = UINavigationController(rootViewController: vc);
        
        addChildViewController(nav);
    }
}
